<template>
  <el-cascader
    popper-class="cascader-hide-radio-new"
    ref="areaRef"
    v-model="area"
    :props="treeProps"
    placeholder="请选择所属区域"
    :disabled="disabled"
    :style="{ width: width }"
    :clearable="false"
    @change="changeSelect"
  />
</template>

<script setup>
import { useUserStore } from '@/pinia/modules/user'

import { get_area_list_by_parentcode } from '@/api/system'
import { get_user_area, get_city_org } from '@/api/api'
import { useVModels } from '@vueuse/core'
import { computedAsync } from '@vueuse/core'
import { isNil } from 'lodash-es'

const props = defineProps({
  prop: {
    type: String,
    default: ''
  },
  clearable: {
    type: Boolean,
    default: false
  },
  width: {
    type: String,
    default: '500px'
  },
  // 父子强制关联 true:可选任意一级  false:只能选中最后一级
  strictly: {
    type: Boolean,
    default: true
  },
  disabled: {
    type: Boolean,
    default: false
  },
  city: {
    type: String,
    default: ''
  },
  org: {
    type: String,
    default: ''
  }
})
const area = ref([props.city])
const areaRef = ref(null)

const treeProps = computed(() => {
  if (areaRef.value) {
    return {
      lazy: true,
      label: 'name',
      checkStrictly: true,
      lazyLoad: async (node, resolve) => {
        const { data, level } = node
        if (data && data.children && data.children.length !== 0) {
          return resolve([])
        }
        if (level === 0) {
          // 获取全部省份
          const r = await get_user_area()
          const targetData = []
          for (const item of r.data) {
            const temp = {
              id: item.id,
              name: item.name,
              value: item.id,
              leaf: false
            }
            targetData.push(temp)
          }
          resolve(targetData)
        } else {
          // 根据省ID获取市
          const r = await get_city_org({ areaCode: data.id })
          const targetData = []
          for (const item of r.data) {
            const temp = {
              id: item.id,
              name: item.orgName,
              value: item.id,
              leaf: true
            }
            targetData.push(temp)
          }
          //   const pathLabels = areaRef.value.getCheckedNodes()[0]
          resolve(targetData)
        }
      }
    }
  } else {
    return {}
  }
})

const emit = defineEmits(['update:city', 'update:org'])
const changeSelect = val => {
  emit('update:city', val[0])
  emit('update:org', val[1])
  areaRef.value.togglePopperVisible(false)
}

const getArea = code => {
  return get_area_list_by_parentcode(code)
}
</script>
<style lang="scss" scoped></style>
